from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.template.context import RequestContext
from django.template import TOKEN_BLOCK, Token

from pages.templatetags.pages_tags import do_placeholder, PlaceholderNode
from sorl.thumbnail.templatetags.thumbnail import thumbnail

from pages_images_extension.models import Image

register = template.Library()

@register.tag
def image_placeholder(parser, token):
    split_token = token.split_contents()
    
    if len(split_token) == 4 or len(split_token) == 2:
        token_string = ' '.join(split_token[0:2])
        token_string += ' with pages_images_extension.widgets.ImageField'
        if len(split_token) == 4:
            token_string += ' '
            token_string += ' '.join(split_token[2:4])
    else:
        token_string = ' '.join(split_token)
        
    placeholder_token = Token(TOKEN_BLOCK, token_string)
    return ImagePlaceholderNode(do_placeholder(parser, placeholder_token))

class ImagePlaceholderNode(PlaceholderNode):
    def __init__(self, placeholder_node, *args, **kwargs):
        self.placeholder_node = placeholder_node
    
    def __getattr__(self, attr):
        return self.placeholder_node.__getattribute__(attr)

    def __setattr__(self, key, value):
        if key == "placeholder_node":
            super(ImagePlaceholderNode, self).__setattr__('placeholder_node', value)
        else:
            self.__getattribute__('placeholder_node').__setattr__(key, value)
    
    def render(self, context):
        ''' Pages uses _test_ as server_name in a dummy admin rendered contex
            In admin context, we don't want to render the content of the node,
            but instead render the admin placeholder '''
        if (isinstance(context, RequestContext)
            and not context['request'].META['SERVER_NAME'] == 'test'):
            page = context['current_page']
            placeholder = self.placeholder_node.name
            image = Image.objects.get_or_create(
                placeholder_name=placeholder,
                page=page)[0]
            if self.placeholder_node.as_varname is None:
                return image.image_file
            else:
                context[self.as_varname] = image.image_file
                return ''
        else:
            return self.placeholder_node.render(context)
